package main

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"net/url"
	"strings"
)

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
	uri := r.RequestURI
	fmt.Println(uri)
	dial, _ := net.Dial("tcp", uri)
	println(uri)
	_, err := io.Copy(w, dial)
	if err != nil {
		fmt.Errorf(err.Error())
	}
}

//func tcpProxy() {
//	listen, err := net.Listen("tcp", ":10012")
//	if err != nil {
//		println(err)
//		return
//	}
//	accept, _ := listen.Accept()
//
//	go func() {
//		accept.Close()
//	}()
//
//}
//func main() {
//	http.HandleFunc("/", ServeHTTP)
//	http.ListenAndServe("127.0.0.1:1568", nil)
//
//}

var port string

func init() {
	flag.StringVar(&port, "port", "1568", "please port [:1568]")
}

func main() {
	flag.Parse() //暂停获取参数
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	log.Println("port:[" + port + "]")
	l, err := net.Listen("tcp", ":"+port)
	if err != nil {
		log.Panic(err)
	}

	for {
		client, err := l.Accept()
		if err != nil {
			log.Panic(err)
		}

		go handleClientRequest(client)
	}
}

func handleClientRequest(client net.Conn) {
	if client == nil {
		return
	}
	defer client.Close()

	var b [1024]byte
	n, err := client.Read(b[:])
	if err != nil {
		log.Println(err)
		return
	}
	var method, host, address string
	fmt.Sscanf(string(b[:bytes.IndexByte(b[:], '\n')]), "%s%s", &method, &host)
	hostPortURL, err := url.Parse(host)
	if err != nil {
		log.Println(err)
		return
	}

	if hostPortURL.Opaque == "443" { //https访问
		address = hostPortURL.Scheme + ":443"
	} else {                                            //http访问
		if strings.Index(hostPortURL.Host, ":") == -1 { //host不带端口， 默认80
			address = hostPortURL.Host + ":80"
		} else {
			address = hostPortURL.Host
		}
	}

	//获得了请求的host和port，就开始拨号吧
	server, err := net.Dial("tcp", address)
	if err != nil {
		log.Println(err)
		return
	}
	if method == "CONNECT" {
		fmt.Fprint(client, "HTTP/1.1 200 Connection established\r\n\r\n")
	} else {
		server.Write(b[:n])
	}
	//进行转发
	go io.Copy(server, client)
	io.Copy(client, server)
}
